/**
 * 云存储。当前适配阿里云与腾讯云。
 */
const models = require('../../utils/models');
const ObjectId = require('../../utils/objectid');

module.exports = class NetStorage extends think.Model {
    /**
     * 生成一个上传至云存储的凭据，供客户端使用。
     */
    async createCredential() {
        const settingModel = think.model(models.Settings);
        const settings = await settingModel.getServerSideSettings();

        const vendor = settings['netStorage'].vendor;
        const vendorConfig = settings['netStorage'][vendor];
        const baseParams = vendorConfig.baseParams;

        const remoteFileName = `/${vendorConfig.upload.filePath}${new ObjectId().toString()}.mp4`;

        if (vendor === 'ali') {
            const accessKey = vendorConfig.accessKey;

            const OssModel = think.model(models.VendorAliOss);
            const credential = OssModel.createCredential(vendorConfig.policy, accessKey.secret);

            return {
                url: baseParams.url,
                fileName: remoteFileName,
                formData: {
                    key: remoteFileName,
                    OSSAccessKeyId: accessKey.id,
                    policy: credential.policy,
                    signature: credential.signature,
                    success_action_status: 200
                }
            }
        } else if (vendor === 'tencent') {
            const cosModel = think.model(models.VendorTencentCos);
            const auth = cosModel.createAuthorization(vendorConfig, remoteFileName);
            return {
                url: auth.cosUrl + remoteFileName,
                fileName: remoteFileName,
                formData: {
                    op: 'upload'
                },
                authorization: auth.signature
            };
        }
    }

    /**
     * 上传文件至云存储。成功返回文件URL。
     */
    async uploadFile(localFilePath, remoteFileName, deleteAfterUploaded) {
        const settingModel = think.model(models.Settings);
        const settings = await settingModel.getServerSideSettings();
        const vendor = settings['netStorage'].vendor;
        const vendorConfig = settings['netStorage'][vendor];

        let remoteFilePath = null;
        if (vendor === 'ali') {
            const OssModel = think.model(models.VendorAliOss);
            remoteFilePath = await OssModel.uploadFile();
        } else if (vendor === 'tencent') {
            const cosModel = think.model(models.VendorTencentCos);
            remoteFilePath = await cosModel.uploadFile(vendorConfig, localFilePath, remoteFileName, deleteAfterUploaded);
        }

        return vendorConfig.cdnBase + remoteFilePath.url;
    }
};